'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import InventoryAdjustModal from '@/components/InventoryAdjustModal';

interface InventoryItem {
  id: number;
  productId: number;
  productName: string;
  productSku: string;
  productPrice: number;
  quantity: number;
  lowStockThreshold: number;
  updatedAt: string;
}

export default function InventoryPage() {
  const [inventory, setInventory] = useState<InventoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [adjustModalOpen, setAdjustModalOpen] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState<InventoryItem | null>(null);

  useEffect(() => {
    fetchInventory();
  }, []);

  const fetchInventory = async () => {
    try {
      const response = await fetch('/api/inventory');
      if (response.ok) {
        const data = await response.json();
        setInventory(Array.isArray(data) ? data : []);
      } else {
        console.error('获取库存数据失败:', await response.json());
        setInventory([]);
      }
    } catch (error) {
      console.error('获取库存数据失败:', error);
      setInventory([]);
    } finally {
      setLoading(false);
    }
  };

  const getStockStatus = (current: number, threshold: number) => {
    if (current === 0) return '无库存';
    if (current <= threshold) return '库存不足';
    return '库存充足';
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case '无库存': return 'text-red-600';
      case '库存不足': return 'text-orange-600';
      default: return 'text-green-600';
    }
  };

  const handleAdjustClick = (product: InventoryItem) => {
    setSelectedProduct(product);
    setAdjustModalOpen(true);
  };

  const handleAdjustInventory = async (adjustData: { 
    productId: number; 
    adjustment: number; 
    type: 'in' | 'out'; 
    notes: string 
  }) => {
    try {
      const response = await fetch('/api/inventory/adjust', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(adjustData),
      });

      if (response.ok) {
        // 刷新库存数据
        fetchInventory();
        alert('库存调整成功！');
      } else {
        const errorData = await response.json();
        alert('库存调整失败: ' + (errorData.error || '未知错误'));
      }
    } catch (error) {
      console.error('调整库存失败:', error);
      alert('库存调整失败，请重试');
    }
  };

  const handleCloseModal = () => {
    setAdjustModalOpen(false);
    setSelectedProduct(null);
  };

  if (loading) return <div className="p-8">加载中...</div>;

  return (
    <div className="p-8">
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <Link href="/" className="text-gray-600 hover:text-gray-900">
            ← 返回首页
          </Link>
          <h1 className="text-3xl font-bold">库存管理</h1>
        </div>
        <div className="flex space-x-3">
          <Link href="/inventory/new" className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
            添加库存
          </Link>
          <button className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">
            导出库存报表
          </button>
          <Link href="/inventory/check" className="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700">
            库存盘点
          </Link>
        </div>
      </div>

      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="p-4 bg-gray-50 border-b">
          <div className="flex space-x-4">
            <input
              type="text"
              placeholder="搜索产品名称或SKU..."
              className="px-3 py-2 border border-gray-300 rounded-md w-64"
            />
            <select className="px-3 py-2 border border-gray-300 rounded-md">
              <option>所有库存状态</option>
              <option>库存不足</option>
              <option>无库存</option>
              <option>库存充足</option>
            </select>
          </div>
        </div>

        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                产品名称
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                SKU
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                当前库存
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                库存阈值
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                库存状态
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                最后更新
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {inventory.map((item) => {
              const status = getStockStatus(item.quantity, item.lowStockThreshold);
              const statusColor = getStatusColor(status);
              
              return (
                <tr key={item.id}>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    {item.productName}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {item.productSku}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {item.quantity}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {item.lowStockThreshold}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm">
                    <span className={`${statusColor} font-medium`}>
                      {status}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {new Date(item.updatedAt).toLocaleDateString('zh-CN')}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button 
                      onClick={() => handleAdjustClick(item)}
                      className="text-blue-600 hover:text-blue-900 mr-3"
                    >
                      调整库存
                    </button>
                    <Link 
                      href={`/inventory/history?productId=${item.productId}`}
                      className="text-green-600 hover:text-green-900"
                    >
                      库存记录
                    </Link>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div className="mt-6 grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
          <h3 className="text-lg font-semibold text-yellow-800 mb-2">库存预警</h3>
          <p className="text-2xl font-bold text-yellow-600">
            {inventory.filter(item => item.quantity > 0 && item.quantity <= item.lowStockThreshold).length}
          </p>
          <p className="text-sm text-yellow-600">需要立即补货的产品</p>
        </div>
        
        <div className="bg-red-50 border border-red-200 rounded-lg p-4">
          <h3 className="text-lg font-semibold text-red-800 mb-2">缺货产品</h3>
          <p className="text-2xl font-bold text-red-600">
            {inventory.filter(item => item.quantity === 0).length}
          </p>
          <p className="text-sm text-red-600">库存为零的产品</p>
        </div>
        
        <div className="bg-green-50 border border-green-200 rounded-lg p-4">
          <h3 className="text-lg font-semibold text-green-800 mb-2">总库存价值</h3>
          <p className="text-2xl font-bold text-green-600">
            ¥{inventory.reduce((sum, item) => sum + (item.quantity * (item.productPrice || 0)), 0).toLocaleString()}
          </p>
          <p className="text-sm text-green-600">当前库存总价值</p>
        </div>
      </div>

      <InventoryAdjustModal
        isOpen={adjustModalOpen}
        onClose={handleCloseModal}
        onAdjust={handleAdjustInventory}
        product={selectedProduct}
      />
    </div>
  );
}